// pages/component/interview/interview.js
let myBehavior = require("../../../utils/dataInit")
const app = getApp()

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [myBehavior],
  properties: {
    interview: Object,
    changetpId: Number
  },
  data: {
    src: "",
    campusArray: ['兴庆校区', '雁塔校区'],
    //把index的初始值设为空和设置一个具体数字是不一样的 若index=-1那么选择器下标就会从-1开始
    index: '',
    choiceMsg: ['', '', '', ''],
    dateArray: [],
    dateIndex: '',
    timeArray: [],
    timeIndex: '',
    timeId: '',
    placeArray: [],
    placeIndex: '',
    tpId: '',
    date_time_place: {
      date: '',
      time: '',
      place: ''
    },
    //只要用户输对了学号 不要出现第一次输是新学号而没提交之前第二次输是已存在用户 那么这个参数就没啥用
    //就是为了清空之前的选择 而只显示用户已存在的报名信息
    isEmpty: false,
    //判断是否为已经报名的学生
    hasSignUp: false,
    changeIdarray: [],
    changeId: ''
  },
  attached() {
    this.dataInit()
  },
  methods: {
    // zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    // zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    // 对于已经存在的用户 实现显示其报名日期地点等信息
    _dataInit() {
      for (let key in this.properties.interview) {
        var empty = this.properties.interview[key] == ''
      }
      if (!empty) {
        this.setData({
          'index': '',
          'dateArray': [],
          'dateIndex': '',
          'timeArray': [],
          'timeIndex': '',
          'placeArray': [],
          'placeIndex': '',
          'isEmpty': true
        })
        var date_time = this.properties.interview['date_time']
        // 将yyyy-mm-dd hh:mm:ss 进行拆分
        var date = date_time.split("T")[0]
        var time = date_time.split("T")[1]
        // 向数组中传递一个对象变量
        var a = date

        this.data.dateArray.push(date)
        var b = time


        this.data.timeArray.push(b)
        var c = {}
        c.tpId = this.properties.interview.tpId
        c.location = this.properties.interview.place
        c.campus = this.properties.interview.campus
        this.data.placeArray.push(c)
        if (this.data.isEmpty) {
          this.setData({
            'index': parseInt(this.properties.interview.campus) - 1,
            'dateArray': this.data.dateArray,
            'timeArray': this.data.timeArray,
            'placeArray': this.data.placeArray,
            'date_time_place.date': date,
            'date_time_place.time': time,
            'date_time_place.place': this.properties.interview.place,
            'hasSignUp': true,
            'changeId': this.properties.interview.tpId
          })
          console.log('interview.campus' + this.properties.interview.campus)
          this.getPlaceList(this.properties.interview.campus)
          this.getDateList(this.properties.interview.campus, this.data.date_time_place.place)
          this.getTimeList(this.properties.interview.campusChange, this.data.date_time_place.place, this.data.date_time_place.date)

        }
      } else {
        this.setData({
          'index': '',
          'dateArray': [],
          'dateIndex': '',
          'timeArray': [],
          'timeIndex': '',
          'placeArray': [],
          'placeIndex': '',
          'date_time_place.date': '',
          'date_time_place.time': '',
          'date_time_place.place': '',
          'hasSignUp': false,
          'changeId': ''
        })
      }
    },
    // zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    //  _datainit函数所调用的函数
    // 提前请求数据 为了避免二次修改的时候还要从校区开始选择

    // ****************************
    getPlaceList(Campus) {
      var that = this
      let aa = wx.getStorageSync("token")
      wx.request({
        url: 'https://zhaoxin2021.tiaozhan.com/api/place',
        header: {
          // 'cookie':"EGG_SESS=HZNkpVewFpgjSJbOUKPhWxWqlYYi3huKKuFj9hdc7iT51llMYqCUc_Cu7NAgwgamSJt22_MsT5FK4CdAtWKWq_7WZg7iXQMpuXqcYCt1O9BBVYxoRwkEbSc8ZEiklojohstnULEzy44Z10KzJ7qO0GfA8iIemzOa5aH0QdUe-8d5VEYW78xu3dy9GrTH57MP; path=/; max-age=86400; expires=Sat 17 Jul 2021 09:28:06 GMT; httponly"
          'cookie': aa
        },
        data: {
          'campus': Campus,
          'limit': 10,
          'page': 1
        },
        method: 'GET',
        success(res) {
          console.log(res)
          if (res.data.success == 1) {
            if (res.data.data.list.length != 0) {
              console.log(res.data.data.list)
              let tempx = []
              let data_index = 0
              let flag = -1
              for (let i = 0; i < res.data.data.list.length; i++) {
                tempx.push(res.data.data.list[i])
              }
              var a = that.data.date_time_place.place
              for (let j = 0; j < tempx.length; j++) {
                if (tempx[j].location == a) {
                  data_index = j
                  flag = 1
                  break
                }
              }
              if (flag == -1) {
                tempx.push(that.data.placeArray[0])
                data_index = tempx.length - 1
              }
            


              that.setData({
                "placeArray": tempx,
                'placeIndex': data_index
              })
            } else {
              that.setData({
                'placeIndex': 0
              })
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.errMsg
            })
          }
        }
      })
    },
    /***************************** */

    getDateList(campus, location) {
      var that = this
      let aa = wx.getStorageSync("token")

      wx.request({
        url: 'https://zhaoxin2021.tiaozhan.com/api/timeplace/queryDate',
        header: {
          // 'cookie':"EGG_SESS=HZNkpVewFpgjSJbOUKPhWxWqlYYi3huKKuFj9hdc7iT51llMYqCUc_Cu7NAgwgamSJt22_MsT5FK4CdAtWKWq_7WZg7iXQMpuXqcYCt1O9BBVYxoRwkEbSc8ZEiklojohstnULEzy44Z10KzJ7qO0GfA8iIemzOa5aH0QdUe-8d5VEYW78xu3dy9GrTH57MP; path=/; max-age=86400; expires=Sat 17 Jul 2021 09:28:06 GMT; httponly"
          'cookie': aa,
        },
        data: {
          'limit': 20,
          'page': 1,
          'campus': campus,
          'location': location

        },
        method: 'GET',

        success(res) {
          if (res.data.success == 1) {
            if (res.data.data.count != 0) {
              let date_index = 0
              let flag = -1
              let dateArr = res.data.data.list
              for (var i = 0; i < dateArr.length; i++) { dateArr[i] = dateArr[i].slice(0, 10) }
/***************************************************************** */
              for (let k = 0; k < dateArr.length; k++) {
                for (let m = dateArr.length - 1; m > k; m--) {
                  let arr = Date.parse(dateArr[m].replace(/-/g, "/"))
                  let arrbe = Date.parse(dateArr[m-1].replace(/-/g, "/"))
                  if (arr < arrbe) {
                    let obj = dateArr[m]
                    dateArr[m] = dateArr[m - 1]
                    dateArr[m - 1] = obj
                  }
                }
              }
/********************************************************************************* */              
              for (let j = 0; j < dateArr.length; j++) {
                if (that.data.dateArray[0] == dateArr[j]) {
                  date_index = j
                  flag = 0
                
                  break
                }
        
              }
              console.log('yyy'+date_index)
              console.log(dateArr.length)
              if (flag != 0) {
                dateArr.push(that.data.dateArray[0])
                date_index = dateArr.length - 1
              }
              console.log('date_index' + date_index)
              that.setData({
                'dateArray': dateArr,
                'dateIndex': date_index

              })
              console.log('kkk'+date_index)
            } 
            
            
   /**************8888888888888888888888888 */         
            else {
              that.setData({
                'dateIndex': 0
              })
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.errMsg
            })
          }
        }
      })
    },
    getTimeList(campus, location, startDate) {
      var tcampus = campus
      var tlocation = location
      var tstartDate = startDate
      var that = this
      var date = new Date(Date.parse(tstartDate.replace(/-/g, "/")) + 86400000)
      var tdate = date.toLocaleDateString()
      let temptime = []
      let tempid = []
      wx.request({
        url: 'https://zhaoxin2021.tiaozhan.com/api/timeplace/queryTime',
        data: {
          "limit": 50,
          'page': 1,
          'campus': tcampus,
          'location': tlocation,
          'startDate': tstartDate,
          'endDate': tdate
        },
        success(res) {

          if (res.data.success == 1) {
            // mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

            let tempt = res.data.data.list
            for (var i = 0; i < tempt.length; i++) {
              if (tempt[i].isChosen < 2 && tempt[i].isChosen >= 0) {
                temptime.push(tempt[i].time)
                tempid.push(tempt[i].id)
              }
            }
            for (let k = 0; k < temptime.length; k++) {
              for (let m = temptime.length - 1; m > k; m--) {
                let tarr = temptime[m]
                let tarrbe = temptime[m-1]
                if (tarr < tarrbe) {
                  let obj = temptime[m]
                  temptime[m] = temptime[m - 1]
                  temptime[m - 1] = obj
                }
              }
            }

            if (temptime.length != 0) {
              /****************************************************************** */
              let date_index = 0
              let flag = -1
              for (var j = 0; j < temptime.length; j++) {

                if (that.data.timeArray[0] == temptime[j]) {
                  date_index = j
                  flag = 0
                  break
                }
              }
              if (flag != 0) {
                temptime.push(that.data.timeArray[0])
                tempid.push(that.data.changeId)
                date_index = temptime.length - 1
              }
              that.setData({
                'timeArray': temptime,
                'timeIndex': date_index,
                'changeIdarray': tempid,
                'changetpId': tempid[date_index]

              })
            } else {
              that.setData({
                'timeIndex': 0
              })
            }
            //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm   
          }

        }
      })
      this.triggerEvent("syncid", this.data.changeId)
    },


    //  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

    campusChange: function (e) {
      if (this.data.index !== '') {
        //调用this.data.index的值 是还没有被修改的值
        //判断是否修改校区 若校区修改则清空选择
        let diffCampus = this.data.index == e.detail.value
        if (!diffCampus) {
          this.setData({
            'dateArray': [],
            'dateIndex': '',
            'timeArray': [],
            'timeIndex': '',
            'placeArray': [],
            'placeIndex': '',
            'date_time_place.date': '',
            'date_time_place.time': '',
            'date_time_place.place': '',
            "userInfo[3].time_place": ''
          })
          // checkInfo界面显示的信息 控制校区和其他信息是分开的
          // 因此需要在更换校区时清空原来的选择 并且要传递过去(针对已报名的学生修改信息
          this.triggerEvent('syncInterviewMsg', this.data.date_time_place)
          wx.showLoading({
            title: '地点加载中'
          })
        }
      } else {
        wx.showLoading({
          title: '地点加载中'
        })
      }
      var campusIndex = parseInt(e.detail.value) + 1
      this.setData({
        'index': e.detail.value,
        'inUserInfo[3].campus': campusIndex,
        'userInfo[3].campus': campusIndex,
      })
      this.triggerEvent("sync", this.data.userInfo)
      var that = this //回调函数中的this指向
      wx.request({
        url: "https://zhaoxin2021.tiaozhan.com/api/place",
        data: {
          limit: 10,
          page: 1,
          campus: this.data.inUserInfo[3].campus
        },

        method: 'GET',

        success(res) {
          setTimeout(() => {
            wx.hideLoading()
            if (res.data.success == 1) {
              if (res.data.data.count != 0) {
                console.log(res.data.data.list)
                that.setData({
                  'placeArray': res.data.data.list
                })

              } else {
                if (that.data.hasSignUp) {
                  wx.showModal({
                    title: '提示',
                    content: '当前校区没有其他空余地点若保持您原来的选择，请直接退出；若仍要更改选择，请联系社团负责人',
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '当前校区没有空余的面试时间或地点，请重新进行选择或者联系社团负责人',
                    success: function (res) {
                      that.setData({
                        'index': '',
                        'inUserInfo[3].campus': '',
                        'userInfo[3].campus': '',
                      })
                    }
                  })
                }
              }
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.errMsg
              })
            }
          }, 1000)
        }
      })

    },
    // zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

   
    placeChange(e) {
      // ###############################################
      if (this.data.placeIndex !== '') {
        let isDateChange = this.data.placeArray[this.data.placeIndex].location == e.detail.value
        if (!isDateChange) {
          this.setData({
            'dateArray': [],
            'dateIndex': '',
            'timeArray': [],
            'timeIndex': '',
            'date_time_place.time': '',
            'date_time_place.date': '',
            "userInfo[3].time_place": ''
          })
          // 若已经报名的学生修改信息 即使选择框已经清空
          // 憨憨行为：只选择了日期就点了提交 其实是可以提交上的 因为tpId的信息没有清空
          // 因此需要将userInfo中的tpId清空 ↓
          this.triggerEvent("sync", this.data.userInfo)
          wx.showLoading({
            title: '日期加载中'
          })
        }
      }else {
        wx.showLoading({
          title: '日期加载中'
        })
      }


      // ##################################
      this.setData({
        "placeIndex": e.detail.value,
        "userInfo[3].time_place": this.data.placeArray[e.detail.value].id,
        'date_time_place.place': this.data.placeArray[e.detail.value].location
      })
      console.log('xxx' + this.data.placeArray[e.detail.value].location)
      console.log(this.data.index)

      var that = this
      let tcampus = parseInt(this.data.index) + 1
      console.log('tcampus' + tcampus)
      let aa = wx.getStorageSync("token")
      wx.request({
        url: 'https://zhaoxin2021.tiaozhan.com/api/timeplace/queryDate',
        header: {
          // 'cookie':"EGG_SESS=HZNkpVewFpgjSJbOUKPhWxWqlYYi3huKKuFj9hdc7iT51llMYqCUc_Cu7NAgwgamSJt22_MsT5FK4CdAtWKWq_7WZg7iXQMpuXqcYCt1O9BBVYxoRwkEbSc8ZEiklojohstnULEzy44Z10KzJ7qO0GfA8iIemzOa5aH0QdUe-8d5VEYW78xu3dy9GrTH57MP; path=/; max-age=86400; expires=Sat 17 Jul 2021 09:28:06 GMT; httponly"
          'cookie': aa,
        },
        data: {
          limit: 20,
          page: 1,
          campus: tcampus,
          location: this.data.date_time_place.place

        },
        method: 'GET',
        success: function (res) {
          console.log(res)
          setTimeout(() => {
            wx.hideLoading()
            if (res.data.success == 1) {
              if (res.data.data.count != 0) {
                /**********************************88 */

                /********************************** */
                let dateArraytemp = res.data.data.list

               //冒泡排序，孔神的代码给菜狗了思路，孔神yyds
                for (var i = 0; i < dateArraytemp.length; i++) { dateArraytemp[i] = dateArraytemp[i].slice(0, 10) }
                for (let k = 0; k < dateArraytemp.length; k++) {
                  for (let m = dateArraytemp.length - 1; m > k; m--) {
                    let arr = dateArraytemp[m]
                    let arrbe = dateArraytemp[m-1]
                    if (arr < arrbe) {
                      let obj = dateArraytemp[m]
                      dateArraytemp[m] = dateArraytemp[m - 1]
                      dateArraytemp[m - 1] = obj
                    }
                  }
                }
                that.setData({
                  "dateArray": dateArraytemp
                })
              } else {
                if (that.data.hasSignUp) {
                  wx.showModal({
                    title: '提示',
                    content: '当前选择下没有其他空余的面试日期。若保持您原来的选择，请直接退出；若仍要更改选择，请联系社团负责人',
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '当前选择下没有空余的面试日期，请重新进行选择或者联系社团负责人',
                    success: function (res) {
                      that.setData({
                        'dateIndex': '',
                        'dateArray': [],
                        'date_time_place.date': '',
                        'timeArray': [],
                        'timeIndex': '',
                        // 'placeArray': [],
                        // 'placeIndex': ''
                      })
                    }
                  })
                }
              }
            } else {
              that.setData({
                'dateIndex': '',
                'date_time_place.date': '',
                'timeArray': [],
                'timeIndex': '',

                // 'placeArray': [],
                // 'placeIndex': ''
              })
              wx.showModal({
                title: '提示',
                content: res.data.errMsg
              })
            }
          }, 1000)

        },
        fail: function (res) {
          console.log("失败");
          console.log(res);
        }
      })
      this.triggerEvent("sync", this.data.userInfo)
      this.triggerEvent("syncInterviewMsg", this.data.date_time_place)
    },




    dateChange: function (e) {

      // 0 == '' true
      // 0 === '' false
      if (this.data.dateIndex !== '') {
        let isDateChange = this.data.dateIndex == e.detail.value
        if (!isDateChange) {
          this.setData({
            'timeArray': [],
            'timeIndex': '',
            'date_time_place.time': '',
            "userInfo[3].time_place": ''
          })
          // 若已经报名的学生修改信息 即使选择框已经清空
          // 憨憨行为：只选择了日期就点了提交 其实是可以提交上的 因为tpId的信息没有清空
          // 因此需要将userInfo中的tpId清空 ↓
          this.triggerEvent("sync", this.data.userInfo)
          wx.showLoading({
            title: '时间加载中'
          })
        }
      }else {
        wx.showLoading({
          title: '时间加载中'
        })
      }
      this.setData({
        'dateIndex': e.detail.value,
        'date_time_place.date': this.data.dateArray[e.detail.value],
        'date_time_place.place': this.data.placeArray[this.data.placeIndex].location,

      })
      this.triggerEvent('syncInterviewMsg', this.data.date_time_place)
      var that = this
      var tempid = this.data.placeIndex
      let tcampus = parseInt(this.data.index) + 1

      //******************************startDate和endDate的处理 */
      let aa = wx.getStorageSync("token")
      var strTime = this.data.date_time_place.date
      var date = new Date(Date.parse(strTime.replace(/-/g, "/")) + 86400000)
      var tdate = date.toLocaleDateString()
      //***********************************************************************************针对isChosen的筛选 */  
      wx.request({
        url: 'https://zhaoxin2021.tiaozhan.com/api/timeplace/queryTime',
        header: {
          // 'cookie':"EGG_SESS=HZNkpVewFpgjSJbOUKPhWxWqlYYi3huKKuFj9hdc7iT51llMYqCUc_Cu7NAgwgamSJt22_MsT5FK4CdAtWKWq_7WZg7iXQMpuXqcYCt1O9BBVYxoRwkEbSc8ZEiklojohstnULEzy44Z10KzJ7qO0GfA8iIemzOa5aH0QdUe-8d5VEYW78xu3dy9GrTH57MP; path=/; max-age=86400; expires=Sat 17 Jul 2021 09:28:06 GMT; httponly"
          'cookie': aa,
        },
        data: {
          'limit': 50,
          'page': 1,
          'campus': tcampus,
          'location': that.data.date_time_place.place,
          'startDate': strTime,
          'endDate': tdate
        },
        method: 'GET',
        success(res) {
          // console.log(res)
          let temptime = []
          let tempid = []
          setTimeout(() => {
            wx.hideLoading()
            if (res.data.success == 1) {
              if (res.data.data.count != 0) {
                // 这段针对辛洲版后端接口说明文档（招新接口文档，20210722版）
                let tempt = res.data.data.list
                console.log('123')

                for (var i = 0; i < tempt.length; i++) {
                  if (tempt[i].isChosen < 2 && tempt[i].isChosen >= 0) {
                    temptime.push(tempt[i].time)
                    tempid.push(tempt[i].id)
                  }
                }
                for (let k = 0; k < temptime.length; k++) {
                  for (let m = temptime.length - 1; m > k; m--) {
                    let tarr = temptime[m]
                    let tarrbe = temptime[m-1]
                    if (tarr < tarrbe) {
                      let obj = temptime[m]
                      temptime[m] = temptime[m - 1]
                      temptime[m - 1] = obj
                    }
                  }
                }
                
                that.setData({
                  "timeArray": temptime,
                  'changeIdarray': tempid

                })
                // ###########
                if (temptime.length == 0) {
                  console.log('1234567890')
                  wx.showModal({
                    title: '提示',
                    content: '当前选择下没有其他空余的面试时间。若保持您原来的选择，请直接退出；若仍要更改选择，请联系社团负责人',
                  })
                }
                // ###########




              } else {
                if (that.data.hasSignUp) {
                  wx.showModal({
                    title: '提示',
                    content: '当前选择下没有其他空余的面试时间或地点。若保持您原来的选择，请直接退出；若仍要更改选择，请联系社团负责人',
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '当前选择下没有空余的面试时间或地点，请重新进行选择或者联系社团负责人',
                    success: function (res) {
                      that.setData({
                        // 'dateIndex': '',
                        // 'date_time_place.date': '',
                        'timeArray': [],
                        'changeIdarray': [],
                        'timeIndex': '',
                        // 'placeArray': [],
                        // 'placeIndex': ''
                      })
                    }
                  })
                }
              }
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.errMsg
              })
            }
          }, 1000)
        }
      })
      this.triggerEvent("sync", this.data.userInfo)
      this.triggerEvent("syncInterviewMsg", this.data.date_time_place)
    },
    timeChange(e) {
      console.log(this.data.timeArray)
      // #######################################
      if (this.data.timeIndex !== '') {
        let isTimeChange = this.data.timeIndex == e.detail.value
        if (!isTimeChange) {
          this.setData({
            'timeArray': [],
            'changeIdarray': [],
            'changeId': '',
            'timeIndex': '',
            'date_time_place.time': '',
            "userInfo[3].time_place": ''
          }),
            this.triggerEvent("sync", this.data.userInfo)

        }
      } else { }


      // ############################################
      this.setData({
        "timeIndex": e.detail.value,
        // "timeId": this.data.timeArray[e.detail.value]
        'date_time_place.time': this.data.timeArray[e.detail.value],
        'changeId': this.data.changeIdarray[e.detail.value]
      })
      this.triggerEvent("syncid", this.data.changeId)
      this.triggerEvent("sync", this.data.userInfo)
      this.triggerEvent("syncInterviewMsg", this.data.date_time_place)
    },
  }
})


